﻿using ComClassLibrary;
using KeyboardArg;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace CountrySelectionKeyBoard
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 当前页面选择级别 0表示主页
        /// 当前页面选择级别 1表示国家地区选择页
        /// </summary>
        private int _pageDepth = 0;

        private KeyBoardArgs _keyboardArg = new KeyBoardArgs();

        private int _btnCountryHeight = 57;

        private int _btnCountryWidth = 352;

        private int _btnIndexHeight = 76;

        private int _btnIndexWidth = 128;

        private int _btnHorDistance = 28; //水平间距

        private int _btnVerDistance = 21; //垂直间距

        private int _btnIndexHorOffSet = 10;   //水平偏移

        private int _btnIndexVerOffSet = 10;   //垂直偏移 

        private int _btnCountryHorOffSet = 10;   //水平偏移

        private int _btnCountryVerOffSet = 10;   //垂直偏移 

        private int _btnCountryFontSize = 32;   //字体大小

        private int _btnIndexFontSize = 36;   //字体大小

        private string _seletedIndex = "";

        private string _seletedCountry = "";

        private Dictionary<string, string> CountryCodes = null;

        private Dictionary<string, List<CountryCodeMap>> CountryIndexs = null;

        private List<List<string>> listRowIndexs = null;

        public MainWindow()
        {
            InitializeComponent();
        }

        public MainWindow(KeyBoardArgs KeyBoardArgs)
        {
            InitializeComponent();
            SetKeyBoardArg(KeyBoardArgs);
        }

        public bool SetKeyBoardArg(KeyBoardArgs args)
        {
            _keyboardArg = args;
            _pageDepth = 1;        
            if (!string.IsNullOrEmpty(_keyboardArg.Title))
            {
                lblTips.Content = _keyboardArg.Title;
            }
            return true;
        }

        private bool ReadConfig()
        {
            CountryReader config = new CountryReader();
            if (!config.OnReading())
            {
                MessageBox.Show(config.Error);
                return false;
            }
            CountryCodes = config.CountryCodes;
            CountryIndexs = config.CountryIndexs;
            listRowIndexs = config.RowIndexs;
            return true;
        }
 
        private void CreatIndexButtons()
        {
            canButtons.Children.Clear();
            for (int i=0; i< listRowIndexs.Count; i++)
            {
                List<string> letters = listRowIndexs[i];
                for (int r = 0; r < letters.Count; r++)
                {
                    string indexLetter = letters[r];
                    Button btn = CreatIndexButton(indexLetter);
                    canButtons.Children.Add(btn);
                    double left = _btnIndexHorOffSet + r * (_btnIndexWidth + _btnHorDistance);
                    double top = _btnIndexVerOffSet + i * (_btnIndexHeight + _btnVerDistance);
                    btn.SetValue(Canvas.LeftProperty, left);
                    btn.SetValue(Canvas.TopProperty, top);
                }               
            }
        }

        private void CreatCountryButtons(List<string> countries)
        {
            try
            {
                canButtons.Children.Clear();
                for (int i=0; i< countries.Count; i++)
                {
                    string country = countries[i];
                    Button btn = CreatCountryButton(country, i+1);
                    canButtons.Children.Add(btn);
                    double left = _btnCountryHorOffSet + (i % 3) * (_btnCountryWidth + _btnHorDistance);
                    double top = _btnCountryVerOffSet + (i / 3) * (_btnCountryHeight + _btnVerDistance);                   
                    btn.SetValue(Canvas.LeftProperty, left);
                    btn.SetValue(Canvas.TopProperty, top);                   
                }              
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        private Button CreatIndexButton(string name)
        {
            TextBlock tb = new TextBlock()
            {
                Text = name,
                FontSize = _btnIndexFontSize,
                TextWrapping = TextWrapping.Wrap,
                TextAlignment = TextAlignment.Center
            };
            Button btn = new Button
            {
                Name = "button" + "_" + name,
                Content = tb,
                Height = _btnIndexHeight,
                Width = _btnIndexWidth,
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin = new Thickness(10, 10, 0, 0),
                VerticalAlignment = VerticalAlignment.Top,
                Visibility = Visibility.Visible,
                FontSize = _btnIndexFontSize,
                Background = Brushes.LightSkyBlue
            };
            btn.Click += new RoutedEventHandler(btnIndex_click);
            return btn;
        }

        private Button CreatCountryButton(string name, int index)
        {
            TextBlock tb = new TextBlock()
            {
                Text = name,
                FontSize = _btnCountryFontSize,
                TextWrapping = TextWrapping.Wrap,
                TextAlignment = TextAlignment.Center
            };
            Button btn = new Button
            {
                Name = "button" + "_" + index.ToString(),
                Content = tb,
                Height = _btnCountryHeight,
                Width = _btnCountryWidth,
                HorizontalAlignment = HorizontalAlignment.Left,
                Margin = new Thickness(10, 10, 0, 0),
                VerticalAlignment = VerticalAlignment.Top,
                Visibility = Visibility.Visible,
                FontSize = _btnCountryFontSize,
                Background = Brushes.LightSkyBlue
            };
            btn.Click += new RoutedEventHandler(btnCountry_click);
            return btn;
        }

        private void btnIndex_click(object sender, RoutedEventArgs e)
        {
            _pageDepth = 1;
            Button btn = (Button)sender;
            _seletedIndex = ((TextBlock)btn.Content).Text;
            List<CountryCodeMap> listCountries = CountryIndexs[_seletedIndex];
            List<string> countries = listCountries.Select(r => r.Name).ToList();
            CreatCountryButtons(countries);
        }

        private void btnCountry_click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;      
            // 获取返回参数
            UpdateKeyboardArgs(btn);
            //点到最后一级后，发消息回主窗体，并且关闭窗体
            SendMessage();
            this.Close();
        }

        private void buttonClose_Click(object sender, RoutedEventArgs e)
        {
            if (_keyboardArg == null)
            {
                this.Close();
                return;
            }
            int uMsg = (int)MessageType.WM_COPYDATA;
            _keyboardArg.PassageType = SendMessageType.Response;
            _keyboardArg.Content = "";
            _keyboardArg.Command = "Cancel";
            string strMsgText = JsonHandler.ConvertToJsonString(_keyboardArg);
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strMsgText);
            COPYDATASTRUCT_INTPTR cds = new COPYDATASTRUCT_INTPTR();
            cds.dwData = (IntPtr)uMsg;
            cds.cbData = data.Length;
            cds.lpData = Marshal.AllocHGlobal(data.Length);
            Marshal.Copy(data, 0, cds.lpData, data.Length);
            Message.SendMessage(_keyboardArg.MsgReceiver, uMsg, 0, ref cds);
            cds.Free();
            this.Close();
            return;
        }

        private void buttonBackToLast_Click(object sender, RoutedEventArgs e)
        {
            if (_pageDepth == 0)
                return;
            if (_pageDepth == 1)
            {
                _pageDepth--;
                CreatIndexButtons();
            }
            _seletedIndex = "";
        }

        private bool SendMessage()
        {
            if (_keyboardArg.MsgReceiver == IntPtr.Zero)
            {
                MessageBox.Show("句柄错误", "句柄错误");
                return false;
            }
            int uMsg = (int)MessageType.WM_COPYDATA;
            string strMsgText = JsonHandler.ConvertToJsonString(_keyboardArg);
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strMsgText);
            COPYDATASTRUCT_INTPTR cds = new COPYDATASTRUCT_INTPTR();
            cds.dwData = (IntPtr)uMsg;
            cds.cbData = data.Length;
            cds.lpData = Marshal.AllocHGlobal(data.Length);
            Marshal.Copy(data, 0, cds.lpData, data.Length);
            Message.SendMessage(_keyboardArg.MsgReceiver, uMsg, 0, ref cds);
            cds.Free();
            return true;
        }

        private void UpdateKeyboardArgs(Button btn)
        {
            //获取按钮的值
            _seletedCountry = ((TextBlock)btn.Content).Text;
            string value = "";
            string[] array = btn.Name.Split('_');
            if (array.Length != 2)
            {
                MessageBox.Show("获取键值失败, 请检查字典配置是否正确.");
            }
            else
            {
                value = array[1];
            }
            _keyboardArg.PassageType = SendMessageType.Response;
            _keyboardArg.Content = _seletedCountry;
            _keyboardArg.Code = CountryCodes[_seletedCountry];
            _keyboardArg.Command = "OK";
            if (null != btn.Tag)
            {
                _keyboardArg.Tag = btn.Tag.ToString();
            }
        }
    
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ReadConfig();
            CreatIndexButtons();
        }
    }
}
